//
//  WmcTaskSchedulerManager.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/8/3.
//

import AMapSearchKit
import Foundation

// MARK: - [WmcTaskSchedulerKey]

enum WmcTaskSchedulerKey {
    /// 禁止编辑日期弹窗
    case forbidEditDateTip
    /// 定位被拒
    case locationUnauthorizedTip
    /// 断网定位失败提示
    case notNetworkLocationFailureTip
}

// MARK: - [WmcTaskSchedulerModel]

class WmcTaskSchedulerModel {
    /// 任务key
    var key: WmcTaskSchedulerKey?
    /// 执行条件
    var showCondition: (() -> Bool)?
    /// 执行回调
    var exceuteClosure: ((@escaping () -> Void) -> Void)?
}

// MARK: - [WmcTaskSchedulerManager]

class WmcTaskSchedulerManager: NSObject {
    // Lifecycle

    override init() {
        super.init()
    }

    // Internal

    static var shared: WmcTaskSchedulerManager = {
        let manager = WmcTaskSchedulerManager()
        return manager
    }()

    var commonAddress: AMapPOI?

    var continueTaskClosure: () -> Void = {
        shared.isPause = false
        continueTask()
    }

    static func registerTask(key: WmcTaskSchedulerKey, executeCondition: @escaping () -> Bool, exceuteClosure: @escaping (@escaping () -> Void) -> Void) {
        
        let isContain = shared.taskList.contains { model in
            model.key == key
        }
        
        if isContain {
            return
        }
        
        let model = WmcTaskSchedulerModel()
        model.key = key
        model.showCondition = executeCondition
        model.exceuteClosure = exceuteClosure

        shared.taskList.append(model)

        WmcTaskSchedulerManager.continueTask()
    }

    static func continueTask() {
        guard let model = shared.taskList.first else {
            return shared.isPause = false
        }

        if shared.isPause {
            return
        }

        shared.currentExecutionTask = model
        shared.taskList.removeFirst()

        let isExecution: Bool = model.showCondition?() ?? false
        if isExecution {
            model.exceuteClosure?(WmcTaskSchedulerManager.shared.continueTaskClosure)
            shared.isPause = true
        } else {
            shared.isPause = false
            WmcTaskSchedulerManager.continueTask()
        }
    }
    
    static func removeTask(key: WmcTaskSchedulerKey) {
        let idx = shared.taskList.firstIndex { model in
            return model.key == key
        }
        
        if let idx = idx {
            shared.taskList.remove(at: idx)
        }
    }

    static func resetPauseStatus(type: WmcTaskSchedulerKey) {
        if shared.currentExecutionTask?.key == type {
            shared.isPause = false
        }
    }

    // Private

    /// 当前执行任务的key
    private var currentExecutionTask: WmcTaskSchedulerModel?

    /// 任务列表
    private var taskList: [WmcTaskSchedulerModel] = []

    /// 是否暂停
    private var isPause: Bool = false
}
